import React, {
  useRef,
  forwardRef,
  useImperativeHandle,
  useEffect,
} from "react";

// useImperativeHandle需要配合useRef一起用
// 帮助拿到子组件的属性和方法

const Child = forwardRef((props, ref) => {
  // 里面有两个参数,分别是ref和回调函数
  useImperativeHandle(ref, () => {
    return {
      a: 1,
      fn() {
        console.log("fn");
      },
    };
  });
  // const fn = () => {
  //   console.log("fn");
  // }

  return <div>child子组件</div>;
});

const App = () => {
  const child = useRef();

  useEffect(() => {
    console.log(child.current.a);
    child.current.fn();
  }, []);
  return (
    <>
      <h2>useImperativeHandle</h2>
      <Child ref={child} />
    </>
  );
};

export default App;
